package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.MessageDao;
import pojo.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    //把留言存储在messageList
//     public List<Message> messageList = new ArrayList<>();
     public ObjectMapper mapper = new ObjectMapper();

     public MessageDao messageDao = new MessageDao();
    /**
     * 查看留言
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        List<Message> messages = messageDao.selectAll();
        String messJson = mapper.writeValueAsString(messages);
        resp.getWriter().write(messJson);
    }

    /**
     * 新增留言
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Message message = mapper.readValue(req.getInputStream(),Message.class);
        messageDao.insert(message);
        resp.getWriter().write("{\"status\":\"200\"}");
    }
}
